import Vue from 'vue';
import Vuex from '@/vuex';
import a from './a';
import b from './b';

function persists() {
  return (store) => {
    const data = localStorage.getItem('VUEX:STATE');
    if (data) {
      store.replaceState(JSON.parse(data));
    }
    store.subscribe((state) => {
      localStorage.setItem('VUEX:STATE', JSON.stringify(state));
    });
  };
}

Vue.use(Vuex);

const store = new Vuex.Store({
  plugins: [
    persists(),
  ],
  state: {
    age: 10,
  },
  getters: {
    myAge(state) {
      return state.age + 20;
    },
  },
  mutations: {
    changeAge(state, payload) {
      state.age += payload;
    },
  },
  actions: {
    changeAge({ commit }, payload) {
      setTimeout(() => {
        commit('changeAge', payload);
      }, 1000);
    },
  },
  modules: {
    a,
    b,
  },
});
export default store;
